/**
 * 弹框登录
 */
define('components/FramePassport/FramePassport', [
    'components/FramePassport/passport.css',
    'utils/fetchEnhancer',
    'pc/js/utils/XForm',
    'utils/Tab',
    'utils/helpers'], (css, fetch, XForm, Tab, helpers) => {

var Passport = function() {
    this.doc = document;

    this.wrapper = null;

    this.html =
`<div class="framepassport-form-wrapper">
    <span class="framepassport-form-close" id="close"></span>

    <div class="framepassport-tabs-wrapper" id="tabs">
        <span class="active">登录</span>
        <span>注册</span>
    </div>

    <!-- login -->
    <div class="framepassport-item-wrapper">
        <section class="framepassport-item">
            <div><input id="login_account" type="text" class="framepassport-item-input" maxlength="15" placeholder="请输入账号" /></div>
            <p id="login_accounttip" class="framepassport-item-tip framepassport-item-tip-right"></p>
        </section>
        <section class="framepassport-item">
            <span id="passport_eye" class="framepassport-item-eye"></span>
            <div><input id="login_pwd" type="password" class="framepassport-item-input" maxlength="15" placeholder="请输入密码" /></div>
            <p id="login_pwdtip" class="framepassport-item-tip framepassport-item-tip-right"></p>
        </section>
        <section class="framepassport-item">
            <span id="login_verifycode_wrapper" class="framepassport-item-verifycode">点击获取验证码</span>
            <div>
                <input type="text" id="login_verifycode" class="framepassport-item-input" maxlength="6" placeholder="验证码" />
            </div>
            <div class="framepassport-item-tip framepassport-item-tip-right" id="login_verifycodetip"></div>
        </section>

        <section class="framepassport-item">
            <p class="framepassport-item-tip"></p>
        </section>

        <section class="framepassport-item">
            <p class="framepassport-item-tip">
                <a class="framepassport-pullright" target="_blank" href="/forget">忘记密码</a>
            </p>
            <div class="framepassport-item-btn-wrapper">
                <button id="login_btn" type="button" class="framepassport-item-btn framepassport-item-btn-big">登录</button>
            </div>
        </section>
    </div>

    <!-- reg -->
    <div class="framepassport-item-wrapper" style="display: none">
        <section class="framepassport-item">
            <div><input id="reg_account" type="text" class="framepassport-item-input" placeholder="请输入昵称" /></div>
            <p id="reg_accounttip" class="framepassport-item-tip framepassport-item-tip-right"></p>
        </section>
        <section class="framepassport-item">
            <div><input id="reg_pwd" type="text" class="framepassport-item-input" placeholder="请输入密码" /></div>
            <p id="reg_pwdtip" class="framepassport-item-tip framepassport-item-tip-right"></p>
        </section>
        <section class="framepassport-item">
            <div><input id="reg_email" type="text" class="framepassport-item-input" placeholder="请输入邮箱" /></div>
            <p id="reg_emailtip" class="framepassport-item-tip framepassport-item-tip-right"></p>
        </section>
        <section class="framepassport-item">
            <button id="reg_btn_verifycode" type="button" class="framepassport-item-btn framepassport-item-btn-code">获取验证码</button>
            <input id="reg_verifycode" type="text" class="framepassport-item-input" placeholder="请输入验证码" />

            <p id="reg_verifycodetip" class="framepassport-item-tip framepassport-item-tip-right"></p>
        </section>

        <section class="framepassport-item">
            <p class="framepassport-item-tip"></p>
        </section>

        <section class="framepassport-item">
            <p class="framepassport-item-tip">
                <label class="framepassport-pullleft" id="reg_agreementbtn">
                    <span id="reg_agreement" class="framepassport-item-checkbox"></span>
                    <span>我已阅读<a target="_blank" href="/licence.html">《用户使用协议》</a></span>
                </label>
            </p>
            <div class="framepassport-item-btn-wrapper">
                <button id="reg_btn" disabled="disabled" type="button" class="framepassport-item-btn framepassport-item-btn-big">注册</button>
            </div>
        </section>
    </div>
</div>`;
};
Passport.prototype = {
    constructor: Passport,
    initDom: function() {
        this.wrapper = this.doc.createElement('div');
        this.wrapper.className = 'framepassport-mask';
        this.wrapper.innerHTML = this.html;
    },
    initCloseEvent: function() {
        var closeBtn = this.doc.getElementById('close');
        closeBtn.onclick = (e) => {
            this.remove();
        };
    },
    initTabEvent: function() {
        var tabWrapper = this.doc.getElementById('tabs');
        new Tab('', 'active').init(
            tabWrapper.querySelectorAll('span'),
            this.doc.querySelectorAll('.framepassport-item-wrapper'));
    },
    initLoginEvent: function() {
        var _self = this;
        var eye = this.doc.getElementById('passport_eye');
        var verifyWrapper = this.doc.getElementById('login_verifycode_wrapper');
        var loginBtn = this.doc.getElementById('login_btn');
        var f = new XForm();

        eye.onclick = () => {
            if(eye.className.indexOf('open') > 0) {
                eye.parentNode.querySelector('input').setAttribute('type', 'password');
                helpers.removeClass(eye, 'open');

            } else {
                eye.parentNode.querySelector('input').setAttribute('type', 'text');
                helpers.addClass(eye, 'open');
            }
        };

        verifyWrapper.onclick = (e) => {
            var t = e.target;

            t.innerHTML = '';
            t.style.backgroundImage = 'url(/api/verifycode/get?t='+ Math.random() +')';
        };

        f.checkOther('login_account', {
            minLength: 2,
            infoText : '请输入注册时的昵称或邮箱',
            errorText : '请输入注册时的昵称或邮箱'
        });
        f.checkOther('login_pwd', {
            minLength: 6,
            infoText : '请输入密码',
            errorText : '密码最少 6 位哦'
        });
        f.checkOther('login_verifycode', {
            minLength: 4,
            infoText : '请输入验证码',
            errorText : '最少 4 位哦'
        });

        loginBtn.onclick = (e) => {
            var valid = f.validate();

            if(!valid) {
                return;
            }

            var account = _self.doc.getElementById('login_account').value;
            var password = _self.doc.getElementById('login_pwd').value;
            var verifyCode = _self.doc.getElementById('login_verifycode').value;
            var isEmail = f.rulesConfig.email.regular.test(account) ? '1' : '0';

            loginBtn.disabled = true;
            USER_SDK.getInstance().apiLogin({
                account: account,
                password: password,
                verifyCode: verifyCode,
                isEmail: isEmail
            }, (data) => {
                loginBtn.disabled = false;

                if(0 === data.status) {
                    // _self.remove();

                    // XUI.toast.success('登录成功');
                    // USER_SDK.getInstance().frameLoginSuccess();
                    window.location.reload();
                    return;
                }

                if(100004 === data.status) {
                    f.setTipMessage('login_verifycode', '验证码错误');

                } else {
                    f.setTipMessage('login_account', '用户名或密码错误');
                }
            });
        };
    },
    tickDownVerifyBtn: function(x, verifycodeBtn) {
        if(x < 1) {
            verifycodeBtn.innerHTML = '获取验证码';
            verifycodeBtn.disabled = false;

            return;
        }

        verifycodeBtn.innerHTML = '获取中 ('+ x +')';

        setTimeout(() => {
            this.tickDownVerifyBtn(x - 1, verifycodeBtn);
        }, 1000);
    },
    initRegisterEvent: function() {
        var _self = this;
        var btn = this.doc.getElementById('reg_btn');
        var verifycodeBtn = this.doc.getElementById('reg_btn_verifycode');
        var agreement = this.doc.getElementById('reg_agreement');
        var agreementBtn = this.doc.getElementById('reg_agreementbtn');
        var f = new XForm();

        f.checkOther('reg_account', {
            minLength: 2,
            infoText : '告诉我你的昵称',
            errorText : '昵称丢了哟'
        });
        f.checkOther('reg_pwd', {
            minLength: 6,
            infoText : '输入至少 6 位密码',
            errorText : '密码太短啦'
        });
        f.checkEmail('reg_email', {
            minLength: 5,
            infoText : '邮箱用于登录和找回密码',
            errorText : '邮箱出错啦'
        });
        f.checkOther('reg_verifycode', {
            minLength: 4,
            infoText : '请输入验证码',
            errorText : '验证码错啦'
        });

        verifycodeBtn.onclick = (e) => {
            var emailNode = _self.doc.getElementById('reg_email');
            var email = emailNode.value;

            if('' === email) {
                return;
            }

            if(!f.rulesConfig.email.regular.test(email)) {
                return;
            }

            /* button 默认 disabled 就不可点击了
            if(verifycodebtn.disabled) {
                console.log('stopped');
                return;
            } */

            verifycodeBtn.disabled = true;
            this.tickDownVerifyBtn(30, verifycodeBtn);
            fetch('/api/mail/sendregister', {
                method: 'POST',
                body: 'email=' + encodeURIComponent(email)

            }).then(function(data) {
                if(0 === data.status) {
                    emailNode.setAttribute('readonly', 'readonly');
                }
                if(100006 === data.status) {
                    f.setTipMessage('reg_email', '该邮箱已经注册，可以直接登录');
                }
            });
        };

        agreementBtn.onclick = (e) => {
            // 原来是选中状态
            if(agreement.className.indexOf('active') > 0) {
                agreement.className = 'framepassport-item-checkbox';
                btn.disabled = true;

            } else {
                agreement.className = 'framepassport-item-checkbox active';
                btn.disabled = false;
            }
        };

        // submit
        btn.onclick = () => {
            var valid = f.validate();

            if(!valid) {
                return;
            }

            btn.disabled = true;
            USER_SDK.getInstance().apiRegister({
                nick: _self.doc.getElementById('reg_account').value,
                password: _self.doc.getElementById('reg_pwd').value,
                email: _self.doc.getElementById('reg_email').value,
                verifyCode: _self.doc.getElementById('reg_verifycode').value
            }, (data) => {
                btn.disabled = false;

                if(0 !== data.status) {
                    XUI.toast.error('注册失败 ' + data.status);

                } else {
                    XUI.toast.error('注册成功，登录试试吧');
                }
            });
        };
    },
    initEvent: function() {
        this.initCloseEvent();
        this.initTabEvent();
        this.initLoginEvent();
        this.initRegisterEvent();
    },
    render: function(type) {
        this.initDom();

        this.doc.body.appendChild(this.wrapper);

        this.initEvent();
    },
    remove: function() {
        this.doc.body.removeChild(this.wrapper);
    }
};
Passport._instance = null;
Passport.getInstance = () => {
    if(null === Passport._instance) {
        Passport._instance = new Passport();
    }

    return Passport._instance;
};

return Passport;
});
